<template>
  <div class="search">
    <span class="role">角色：</span>
    <el-select v-model="roleId" class="select-role" size="small">
      <el-option
        v-for="item in rolesData"
        :key="item.roleId"
        :label="item.roleName"
        :value="item.roleId"
      />
    </el-select>
    <el-button 
      size="small" 
      type="success" 
      @click="loadTable"
    >查询</el-button>
    <el-button 
      size="small" 
      type="primary" 
      @click="openDrawerHandler"
    >添加</el-button>
  </div>
  <el-table size="small" :data="tableData" style="width: 99%">
    <el-table-column prop="id" label="编号" width="100" />
    <el-table-column prop="loginId" label="账号" width="100" />
    <el-table-column prop="name" label="姓名" />
    <el-table-column prop="phone" label="手机号" width="100" />
    <el-table-column label="头像" width="100">
      <template #default="scope">
        <el-avatar
          :src="scope.row.photo"
          v-if="scope.row.photo"
        />
        <el-avatar :icon="UserFilled" v-else />
        <!-- <el-avatar
          :src="AVATAR_IMG_URL + scope.row.photo"
        /> -->
      </template>
    </el-table-column>
    <el-table-column prop="role.roleName" label="角色名称" width="100" />
    <el-table-column label="操作" width="180">
      <template #default="scope">
        <el-button 
          size="small" 
          type="warning" 
          @click="handleEdit(scope.row)"
        >编辑</el-button>
        <el-button
          size="small"
          type="danger"
          @click="handleDelete(scope.row)"
        >删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <div class="pages">
    <el-pagination background small layout="prev, pager, next" :total="total" :page-size="pageSize" v-model:current-page="pageNo" @current-change="curChange" />
  </div>
  <el-drawer
    v-model="openDrawer"
    :title="`${isAdd ? '添加' : '编辑'}账户`"
    :before-close="handleClose"
  >
    <div class="item">
      <span>头像：</span>
      <div>
        <el-upload
          class="avatar-uploader"
          :action="actionUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :on-error="handleAvatarError"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="formData.photo" :src="formData.photo" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </div>
    </div>
    <div class="item" v-show="isAdd">
      <span>账号：</span>
      <div>
        <el-input v-model="formData.loginId" placeholder="请输入账号" size="mini" />
      </div>
    </div>
    <div class="item" v-show="isAdd">
      <span>密码：</span>
      <div>
        <el-input v-model="formData.loginPwd" type="password" placeholder="请输入密码" size="mini" show-password />
      </div>
    </div>
    <div class="item confirm-password" v-show="isAdd">
      <span>确认密码：</span>
      <div>
        <el-input v-model="formData.loginPwd2" type="password" placeholder="请输入确认密码" size="mini" show-password />
        <p class="passwordTip" v-show="isShowTip">两次输入的密码不一致！</p>
      </div>
    </div>
    <div class="item">
      <span>姓名：</span>
      <div>
        <el-input v-model="formData.name" placeholder="请输入姓名" size="mini" />
      </div>
    </div>
    <div class="item">
      <span>手机号：</span>
      <div>
        <el-input v-model="formData.phone" placeholder="请输入手机号" size="mini" />
      </div>
    </div>
    <div class="item">
      <span>角色：</span>
      <div>
        <el-select v-model="formData.roleId" class="select-role" size="small">
          <el-option
            v-for="item in rolesData"
            :key="item.roleId"
            :label="item.roleName"
            :value="item.roleId"
          />
        </el-select>
      </div>
    </div>
    <div class="item">
      <span></span>
      <div>
        <el-button 
          size="small" 
          type="primary" 
          :disabled="isShowTip"
          @click="editAccount"
        >{{isAdd ? '添加' : '编辑'}}</el-button>
        <el-button 
          size="small" 
          @click="clearInput"
        >重置</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import {reactive, toRefs, watch} from 'vue';
import { ElMessage } from 'element-plus';
import { Plus, UserFilled } from '@element-plus/icons-vue';
import {queryList, addEditAccount, delAccount} from '../../api/admin';
import {getRoleList} from '../../api/role';
import {ADMIN_UPLOAD_URL, AVATAR_IMG_URL} from '../../config/constant';
import {$confirm} from '../../utils/msg';

export default {
  name: 'Account',
  setup(){
    const state = reactive({
      tableData: [], //账户数据
      total: 0, //总条目数
      pageNo: 1, //当前页
      pageSize: 5, //每页显示条数
      roleId: 0, //角色编号-搜索
      rolesData: [], //角色数据
      openDrawer: false, //是否显示 Drawer
      formData: {
        photo: '', //头像
        loginId: '', //账号
        loginPwd: '', //密码
        loginPwd2: '', //确认密码
        phone: '', //手机号
        roleId: 0, //角色编号-添加、编辑
        name: '', //姓名
      },
      isShowTip: false, //是否显示确认密码提示
      actionUpload: ADMIN_UPLOAD_URL, //头像请求 URL
      isAdd: true, //是否添加账户
    });

    watch(
      [() => state.formData.loginPwd, () => state.formData.loginPwd2],
      (value, oldValue) => {
        if(value[1] === state.formData.loginPwd && value[0] === state.formData.loginPwd2){
          //两次密码一致
          state.isShowTip = false;
        }else{
          //两次密码不一致
          state.isShowTip = true;
        }
      }
    );

    //加载账户数据
    const loadTable = async () => {
      const params = {
        pageNo: state.pageNo,
        roleId: state.roleId,
      }

      const res = await queryList(params);

      state.tableData = res.data;
      state.total = res.count;
      state.pageSize = res.pageSize;
      state.pageNo = res.pageNo;
    }

    loadTable();

    //加载角色数据
    const loadRoles = async () => {
      const data = await getRoleList();

      data.unshift({
        roleId: 0,
        roleName: '请选择角色',
      });

      state.rolesData = data;
    }

    loadRoles();

    //current-page 改变时触发
    const curChange = (current) => {
      state.pageNo = current;
      loadTable();
    }

    //打开抽屉
    const openDrawerHandler = () => {
      state.isAdd = true;
      state.openDrawer = true;
    }

    //上传文件之前的钩子
    const beforeAvatarUpload = (rawFile) => {
      if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('头像的格式必须为JPG或PNG!')
        return false
      } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('头像文件大小不能超过2MB!')
        return false
      }
      return true
    }

    //文件上传成功时的钩子
    const handleAvatarSuccess = (
      response,
      uploadFile
    ) => {
      const {success, filename} = response;

      if(success){
        //文件上传成功
        state.formData.photo = AVATAR_IMG_URL + filename;
      }
    }

    //文件上传失败时的钩子
    const handleAvatarError = (error) => {
      const response = {
        success: true,
        filename: 'myAvatar.jpg',
      }
      
      const {success, filename} = response;

      if(success){
        //文件上传成功
        state.formData.photo = AVATAR_IMG_URL + filename;
      }
    }

    //添加、编辑账户
    const editAccount = async () => {
      const result = await addEditAccount(state.formData, state.isAdd);

      if(result){
        //成功
        loadTable();
      }
    }

    //关闭抽屉
    const handleClose = () => {
      state.formData = {
        photo: '', //头像
        loginId: '', //账号
        loginPwd: '', //密码
        loginPwd2: '', //确认密码
        phone: '', //手机号
        roleId: 0, //角色编号-添加、编辑
        name: '', //姓名
      }

      state.openDrawer = false;
    }

    //点击重置按钮
    const clearInput = () => {
      state.formData = {
        photo: '', //头像
        loginId: '', //账号
        loginPwd: '', //密码
        loginPwd2: '', //确认密码
        phone: '', //手机号
        roleId: 0, //角色编号-添加、编辑
        name: '', //姓名
      }
    }

    //点击编辑按钮
    const handleEdit = (row) => {
      state.formData = {
        ...row,
        roleId: row.role.roleId,
      }

      state.isAdd = false;
      state.openDrawer = true;
    }

    //点击删除按钮
    const handleDelete = async (row) => {
      await $confirm('确定删除该账户吗？');

      const result = await delAccount(row);

      if(result){
        //成功
        loadTable();
      }
    }

    return {
      ...toRefs(state),
      curChange,
      loadTable,
      openDrawerHandler,
      beforeAvatarUpload,
      handleAvatarSuccess,
      handleAvatarError,
      editAccount,
      handleClose,
      AVATAR_IMG_URL,
      UserFilled,
      handleEdit,
      handleDelete,
      clearInput,
    }
  },
}
</script>

<style lang="scss" scoped>
.pages {
  padding-top: 10px;
}
.item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  &.confirm-password {
    align-items: baseline;
  }
  span {
    width: 70px;
    font-size: 14px;
    text-align: right;
  }
  div {
    flex: 1;
  }

  $imgLength: 90px;

  .avatar-uploader .avatar {
    width: $imgLength;
    height: $imgLength;
    display: block;
  }
  .passwordTip {
    color: var(--el-color-danger);
    font-size: 12px;
    padding-top: 5px;
  }
}
</style>

<style lang="scss">
$imgLength: 90px;

.el-icon.avatar-uploader-icon {
  font-size: 14px;
  color: #8c939d;
  width: $imgLength;
  height: $imgLength;
  text-align: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
</style>